<template>
    <div style="height: 100%">
        <div class="list-left" :style="{ height: leftHgt }">
            <div class="module" style="height: 100%">
                <div class="left-tree">
                    <el-tree
                        ref="tree1"
                        class="filter-tree"
                        node-key="id"
                        :data="treeData"
                        @node-click="handleNodeClick"
                        :current-node-key="currentNodeKey"
                        highlight-current
                        default-expand-all
                        :expand-on-click-node="false"
                    >
                    </el-tree>
                </div>
            </div>
        </div>

        <div style="height: 100%">
            <div class="list-right">
                <div class="list-right-div">
                    <el-button type="primary" key="table1-btn1" v-if="currentNodeKey === '15'" @click="addTabs('addReminderRules', '')"
                        >新增</el-button
                    >
                    <el-button type="danger" size="mini" key="table1-btn2" @click="handleDelete(tableSelection)">删除</el-button>
                    <el-button type="primary" key="table1-btn3" @click="validSymbolBtn(tableSelection, '1')">启用</el-button>
                    <el-button type="danger" size="mini" key="table1-btn4" @click="validSymbolBtn(tableSelection, '0')">禁用</el-button>
                    <span style="cursor: pointer" title="点击查看条目信息" class="list-right-span" @click="entryVisible = true"
                        >未设置待办提醒规则条目数:&nbsp;&nbsp;<b style="color: red">{{ noRuleSetList.length }}</b></span
                    >
                </div>

                <div style="height: calc(100vh - 170px)">
                    <vxe-table
                        :data="dataSource"
                        :key="tableKey"
                        v-table-top="paging.currentPage"
                        @checkbox-change="handleSelectionChange"
                        @checkbox-all="handleSelectionChange"
                        border
                        ref="xTable"
                        size="mini"
                        style="width: 100%"
                        height="100%"
                        :auto-resize="true"
                        :resizable-config="{ minWidth: '90' }"
                        :filter-config="{ remote: true }"
                        :sort-config="{ remote: true }"
                        @sort-change="handleSelectionChange2"
                        @filter-change="handleFilterChange"
                        @resizable-change="handleResizeChange"
                        show-header-overflow
                        :row-style="{ height: '35px' }"
                        :cell-style="{ padding: '0px' }"
                    >
                        <vxe-column type="checkbox" width="55" size="mini" align="center" :selectable="getSelectableModule" resizable> </vxe-column>
                        <vxe-column field="cRuleId" title="规则编码" min-width="120" sortable :filters="[{ data: '' }]" show-overflow resizable>
                            <template #filter="{ $panel, column }">
                                <el-input
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </template>
                        </vxe-column>
                        <vxe-column field="cRuleName" title="规则名称" min-width="120" sortable :filters="[{ data: '' }]" show-overflow resizable>
                            <template #filter="{ $panel, column }">
                                <el-input
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </template>
                        </vxe-column>
                        <vxe-column
                            field="cStatus"
                            title="启用状态"
                            sortable
                            min-width="120"
                            show-overflow
                            align="center"
                            :filters="[
                                { label: '启用', value: '1' },
                                { label: '禁用', value: '0' },
                            ]"
                            resizable
                        >
                            <template slot-scope="scope">
                                <span :style="getStyle(scope.row['cStatus'])">
                                    {{ stateEnum[scope.row['cStatus']] || '--' }}
                                </span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cMdUser" title="更新人" min-width="120" sortable :filters="[{ data: '' }]" show-overflow resizable>
                            <template #filter="{ $panel, column }">
                                <el-input
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </template>
                        </vxe-column>
                        <vxe-column field="dMdTime" title="更新时间" min-width="160" sortable show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span> {{ dateFormatter(scope.row.dMdDate, scope.row.dMdTime) }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column field="cCtUser" title="创建人" min-width="120" sortable :filters="[{ data: '' }]" show-overflow resizable>
                            <template #filter="{ $panel, column }">
                                <el-input
                                    class="my-input"
                                    type="type"
                                    v-for="(option, index) in column.filters"
                                    :key="index"
                                    v-model="option.data"
                                    @input="$panel.changeOption($event, !!option.data, option)"
                                />
                            </template>
                        </vxe-column>

                        <vxe-column field="dCtTime" title="创建时间" min-width="160" sortable show-overflow align="center" resizable>
                            <template slot-scope="scope">
                                <span> {{ dateFormatter(scope.row.dCtDate, scope.row.dCtTime) }}</span>
                            </template>
                        </vxe-column>

                        <vxe-column title="操作" min-width="230" fixed="right">
                            <template slot-scope="scope">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-view"
                                    topTitle="查看"
                                    @on-click="addTabs('look', scope.row)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-edit"
                                    topTitle="编辑"
                                    @on-click="addTabs('edit', scope.row)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="danger"
                                    icon="el-icon-delete"
                                    topTitle="删除"
                                    @on-click="handleDelete(scope.row.cRuleId)"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-time"
                                    topTitle="预警通知"
                                    @on-click="handleEarlWarning(scope.row)"
                                ></RiskIconButton>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
                <div class="block">
                    <el-pagination
                        background
                        @current-change="currentChange"
                        layout="total, prev, pager, next"
                        :total="dataSource.length"
                        :page-size="paging.pageSize"
                        :current-page.sync="paging.currentPage"
                    >
                    </el-pagination>
                </div>
            </div>
        </div>

        <!-- 删除 -->
        <el-dialog
            drag
            title="确定删除以下规则吗?"
            :visible.sync="deleteVisible"
            width="500px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div class="remove-text">
                <span> {{ delCodeList.join(' , ') }}</span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="deleteVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="submitDeleteNotice">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 禁用/启用 -->
        <el-dialog drag :visible.sync="validSymbolVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="dialog-title">
                <h3>
                    {{ stateType === '1' ? '确定启用以下规则吗?' : '确定禁用以下规则吗?' }}
                    <span style="color: hsl(0deg 65% 51%); font-size: 13px; margin-left: 15px"
                        >(备注: 已自动过滤{{ stateType == '1' ? '已启用' : '已禁用' }}的规则)</span
                    >
                </h3>
            </div>
            <div class="remove-text">
                <span> {{ validCodeList.join(' , ') }}</span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="validSymbolVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="submitValidSymbol">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 查看未设置规则条目 -->
        <el-dialog drag :visible.sync="entryVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="title" class="dialog-title">
                <h3>以下触发类条目未添加待办规则</h3>
            </div>
            <div class="remove-text">
                <span> {{ noRuleSetList.join(' , ') }}</span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="entryVisible = false">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 单个规则发送记录  -->
        <yh-dialog
            drag
            :title="sendRecordTitle"
            :visible.sync="sendRecordVisible"
            width="900px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            id="sendRecord"
            v-if="sendRecordVisible"
        >
            <RuleSendRecord :record="curRuleRecord" />
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="sendRecordVisible = false">取 消</el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import RiskLeftModule02 from '@/common/components/risk-left-module02.vue';
import RiskRightModule02 from '@/common/components/risk-right-module02.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import RiskTable from '@/common/components/risk-table.vue';
import { DialogVO } from '@yhfin/biz';
import { checkPermission, dateFormat, getConfigItem, getCurrentPageData, timeFormat } from '@/utils/tools';
import XEUtils from 'xe-utils';
import { getUser } from '@/utils/user-util';
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import Index from '@/pages/setting/dict';
import * as moment from 'moment';
import { mixins } from 'vue-class-component';
import RiskEmitter from '@/common/mixis/risk-emitter.vue';
import { ColumnVO, TableConfigVO, VueObject } from '@/common/vo';
import RiskTableP from '@/common/components/risk-table-plus.vue';

import API from '@/pages/system-maintence/api/warning-notice';
import RuleSendRecord from '@/pages/system-maintence/warning-notice/rule-send-record.vue';
import WarningNotice from '@/pages/system-maintence/dict/warning-notice';
import { TagsViewModule } from '@/store/modules/tags-view';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
    totalPage?: number;
}

@Component({
    name: 'ReminderRulesList',
    components: { RiskLeftModule02, RiskRightModule02, RiskIconButton, RiskTable, RiskTrantable, RiskTableP, RuleSendRecord },
})
export default class ReminderRulesList extends mixins(RiskEmitter) {
    private dataSource: any[] = []; // 表格数据
    moduleKey: number = -1;

    private treeData: any = [
        {
            label: '全部选择',
            id: '0',
            children: [{ label: '待办提醒', id: '15' }],
        },
    ];

    private validSymbolStorage: any = {
        '1': '启用',
        '0': '禁用',
    };
    private entryVisible: boolean = false; // 未设置待办提醒规则条目显示
    private noRuleSetList: any[] = []; // 未设置待办提醒规则条目编号列表

    private currentNodeKey: string = '0'; // 当前选中节点

    private leftHgt: string = '100%';

    private paging: pages = { currentPage: 1, pageSize: 19979797, totalPage: 0, total: 0 };

    private sort: string = '';

    private tableSelection: any[] = []; // 表格勾选数据

    private delCodeList: string[] = []; // 删除数据

    private deleteVisible: boolean = false; // 删除dialog
    private validSymbolVisible: boolean = false; // 待办规则启用/禁用
    private sendRecordVisible: boolean = false; // 单个规则发送记录
    private sendRecordTitle: string = ''; // 单个规则发送记录

    private curRuleRecord: any = {}; // 单个规则发送记录

    private validCodeList: any[] = []; // 启用/禁用勾选数据
    private stateType: string = '1'; // 0禁用 1启用
    private iconDom: any = null; // 图标dom
    private changeIconCols: any[] = [2, 3];
    private cRuleId: string = '';
    private cRuleName: string = '';
    private cMdUser: string = '';
    private cCtUser: string = '';
    private status: string = '';
    private statusGroup: any[] = [];
    private stateEnum: any = {
        '1': '启用',
        '0': '禁用',
    };
    private tableKey: number = 1;
    tableConfig: TableConfigVO = {
        rowKey: 'ruleId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };

    created() {
        if (sessionStorage.getItem('warnning-notice-treeKey')) {
            this.currentNodeKey = sessionStorage.getItem('warnning-notice-treeKey');
        }
    }

    async mounted() {
        // 根据选中树节点获取待办规则列表
        this.getNoticeList();
        // 获取未设置代办提醒规则的条目列表 todo
        this.getNoRuleSetList();
    }

    // 获取未设置代办提醒规则的条目列表 todo
    private getNoRuleSetList() {
        this.$axios.get('/htscamc/eventRule/stopLossEntry').then((res: any) => {
            this.noRuleSetList = res; // 该数据为未设置代办提醒规则的条目编号数组
        });
    }

    private handleRefresh() {
        this.getNoticeList();
    }

    // 获取待办规则列表
    private getNoticeList(refresh: boolean = false) {
        let url = '/htscamc/eventRule/list';
        let data = {
            cctUser: this.cCtUser,
            cmdUser: this.cMdUser,
            cruleId: this.cRuleId,
            cruleName: this.cRuleName,
            cstatus: this.statusGroup,
            paging: this.paging,
            sort: this.sort,
        };
        this.$axios({ url, method: 'post', data }).then((res: any) => {
            this.dataSource = res.list;
            this.changeTable();
            this.dataSource.forEach(element => {
                element.roleCodes = element.notifier;
                if (element.startTime) {
                    // 补0
                    element.startTime = this.add0(element.startTime.toString() || '');
                }
                if (element.endTime) {
                    // 补0
                    element.endTime = this.add0(element.endTime.toString() || '');
                }
            });
            this.paging.total = res.list.length;
            this.paging.totalPage = res.totalPage;
            refresh && this.yh_message_success('刷新成功');
        });
    }

    add0(time) {
        if (time.length < 6) {
            const addLen = 6 - time.length;
            for (let i = 0; i < addLen; i++) {
                time = '0' + time;
            }
        }
        return time;
    }

    // 表格勾选事件
    private handleSelectionChange(val): void {
        this.tableSelection = val.selection;
    }

    private currentChange(val): void {
        this.paging.currentPage = val;
        this.getNoticeList();
    }

    // 删除事件
    private handleDelete(val): void {
        if (typeof val === 'string') {
            val = [val];
        }
        if (!val.length) {
            this.yh_message_warn('请选择删除项！');
            return;
        }
        this.delCodeList = val.map(item => item.cRuleId || item);
        this.deleteVisible = true;
    }
    // 待办规则删除事件
    private handleDeleteStatic(val): void {}

    // 提交删除
    private submitDeleteNotice() {
        let url = '/htscamc/eventRule/batchDel?ruleIds=' + this.delCodeList; // 批量删除规则

        this.$axios({ url, method: 'post' })
            .then((res: any) => {
                this.yh_message_success('删除成功！');
                this.getNoticeList();
                this.deleteVisible = false;
            })
            .finally(() => {
                // 清除导出时列表勾选项
                /*  this.$nextTick(() => {
                    this.isExit3 && (this.$refs['risk-table'] as any).resetCheckRowKeys();
                }); */
            });
    }
    // 待办规则禁用/启用确认
    private submitValidSymbol() {
        this.$axios({ url: '/htscamc/eventRule/updateStatus?ruleIds=' + this.validCodeList + '&status=' + this.stateType, method: 'post' })
            .then((res: any) => {
                let text = this.stateType === '1' ? '启用成功!' : '禁用成功!';
                this.yh_message_success(text);
                this.getNoticeList();
                this.validSymbolVisible = false;
            })
            .finally(() => {
                // 清除导出时列表勾选项
                /*  this.$nextTick(() => {
                    this.isExit3 && (this.$refs['risk-table'] as any).resetCheckRowKeys();
                }); */
            });
    }

    private validSymbolBtn(val, type) {
        if (typeof val === 'string') {
            val = [val];
        }
        if (!val.length) {
            const text = type === '1' ? '启用' : '禁用';
            this.yh_message_warn('请选择' + text + '项！');
            return;
        }
        // 过滤掉type的数据
        val = val.filter(item => item.cStatus != type);
        if (!val.length) {
            const text = type === '1' ? '启用' : '禁用';
            this.yh_message_warn('您勾选的均已' + text + ',请勾选待' + text + '项！');
            return;
        }
        this.validCodeList = val.map(item => item.cRuleId || item);
        this.validSymbolVisible = true;
        this.stateType = type;
    }

    // 回调函数
    addTabs(data: any, val: any) {
        let datas: any = {};
        datas.type = data;
        // operateType和scheduleType没有返回  todo
        datas.value = val;

        this.dispatch('ReminderRules', 'addTables', datas);

        sessionStorage.setItem('warnning-notice-treeKey', this.currentNodeKey);
    }

    private handleFilterChange({ field, values, datas }): void {
        if (['cRuleId', 'cRuleName', 'cMdUser', 'cCtUser'].includes(field)) {
            this[field] = datas.join('');
        } else if (field === 'cStatus') {
            this['statusGroup'] = values;
        } else {
            this[field] = values;
        }

        this.getNoticeList();
    }

    private handleResizeChange(options: any) {
        this.$nextTick(() => {
            (this.$refs.xTable as any).resetColumn(false);
            // (this.$refs.xTable as any).recalculate(true);
        });
    }
    /*
     * 规则编号：TO_NUMBER(REGEXP_REPLACE(C_RULE_ID,'[^0-9]',''))
     * 规则名称：C_RULE_NAME
     * 更新人：C_MODIFY_USER
     * 更新时间：D_MODIFY_DATE，D_MODIFY_TIME
     * 创建人：C_CREATE_USER
     * 创建时间：D_CREATE_DATE，D_CREATE_TIME
     */
    private handleSelectionChange2(column) {
        console.log(column, 'column');

        let { order, property } = column;

        if (order) {
            order = order.split('ending')[0];
        } else {
            order = '';
        }
        let obj = {
            cRuleId: `TO_NUMBER(REGEXP_REPLACE(C_RULE_ID,'[^0-9]',''))`,
            cRuleName: 'C_RULE_NAME',
            cMdUser: 'C_MD_USER',
            dMdTime: 'D_MD_DATE,D_MD_TIME',
            cCtUser: 'C_CT_USER',
            dCtTime: 'D_CT_DATE,D_CT_TIME',
            cStatus: 'C_STATUS',
        };

        if (property === 'dMdTime' || property === 'dCtTime') {
            let arr;
            arr = obj[property].split(',');
            for (let i = 0; i < arr.length; i++) {
                arr[i] = arr[i] + ' ' + order;
            }
            arr = arr.join(',');
            this.sort = arr;
            this.getNoticeList();
            return;
        }
        // if (property === 'createTime') {
        //     let arr;
        //     arr = obj[property].split(',');
        //     for (let i = 0; i < arr.length; i++) {
        //         arr[i] = arr[i] + ' ' + order;
        //     }
        // }
        this.sort = obj[property] + ' ' + order;
        this.getNoticeList();
    }

    // 节点点击事件
    private handleNodeClick(data: any, node: any): void {
        this.currentNodeKey = data.id;

        this.paging = { currentPage: 1, pageSize: 19979797, totalPage: 0, total: 0 };
        this.ruleId = '';
        this.ruleName = '';
        this.noticeGroup = [];
        this.statusGroup = [];
        this.modifyUser = '';
        this.createUser = '';
        this.status = '';
        this.sort = '';
        this.tableKey++;

        // if (data.id == '1') {
        this.iconDom = null;
        this.getNoticeList();
        // }
    }

    // 时间处理
    private dateFormatter(date, time) {
        if (date || time) {
            return (date ? dateFormat(date, true) : '') + ' ' + (time ? timeFormat(time, true) : '');
        }
        return '--';
    }

    private handleEarlWarning(val: any): void {
        const activeName = '新增待办提醒邮件推送规则';
        /*  this.$router.push({
            path: `/system/notice?activeName=${activeName}`, // 跳转预警通知
        }); */
        localStorage.setItem('DBTX', 'addDBTX');
        top.window.postMessage('/system/notice', '*');
    }

    private formatterValidSymbol(val) {
        return this.validSymbolStorage[val.validSymbol];
    }

    changeTable() {
        this.$nextTick(() => {
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.vxe-icon--funnel');
                for (let i = 0; i < this.iconDom.length; i++) {
                    if (!this.changeIconCols.includes(i)) {
                        this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                    }
                }
            }
        });
    }

    private getStyle(value: string): any {
        let color = '';
        color = value == '1' ? 'green' : value == '0' ? 'red' : '';
        return { color: color };
    }
}
</script>
<style lang="scss" scoped>
.list-left {
    height: 100vh;
    width: 211px;
    border: 1px solid #cacaca;

    .list-heard {
        font-weight: 700;
        font-size: 20px;
        margin: 10px 0px 0px 10px;
    }

    .list-left-div {
        width: 210px;
        height: 40px;
        background: #fff;
        border: 1px solid #cacaca;
        padding-top: 4px;
        padding-left: 10px;
        position: relative;

        .left-p {
            position: absolute;
            right: 5px;
            top: 4px;

            .el-icon-search {
                color: #fff;
            }
        }

        & /deep/ .el-button {
            padding: 6px;
        }
    }

    .left-tree {
        width: 217px;
        height: 50%;
        overflow: scroll;
    }
}
.list-right {
    height: 100%;
    border: 1px solid #cacaca;
    position: absolute;
    top: 0;
    left: 210px;
    width: calc(100% - 210px);

    .list-right-div {
        padding: 0px 10px;
        width: 100%;
        height: 60px;
        line-height: 60px;
        .list-right-span {
            position: absolute;
            right: 60px;
            color: #1a1a1a;
        }
    }
}
#editDialog /deep/ .el-dialog {
    margin-top: 3vh !important;
    .el-dialog__body {
        max-height: 90vh;
    }
}
#sendRecord /deep/ .el-dialog .el-dialog__body {
    max-height: 60vh !important;
}

/deep/ .el-dialog .el-dialog__body .el-date-editor {
    min-width: 140px;
    width: 20%;
}

.ascending:hover {
    border-bottom-color: #409eff;
}

.descending:hover {
    border-top-color: #409eff;
}

.icon-minus {
    text-align: center;
    width: 20px;
    height: 20px;
    line-height: 20px;
    border: 1px solid transparent;

    border-radius: 50%;
    margin: 4px 12px;
}

/deep/ .el-select__tags {
    flex-wrap: nowrap;

    .el-tag.el-tag--info {
        display: flex;
        align-items: center;

        .el-select__tags-text {
            display: block;
            max-width: 120px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
.temp {
    // pointer-events: none;
    cursor: no-drop;
}

/deep/ td {
    border: initial;
}
/deep/ .vxe-table--render-default .vxe-table--fixed-right-wrapper {
    box-shadow: -1px 0px 1px rgba(0, 0, 0, 0.12) !important;
}
</style>
